package project.parser.ast.exps;

import project.environments.DynamicEnv;
import project.environments.StaticEnv;
import project.environments.Value;
import project.parser.ast.aux.AuxExpList;
import project.parser.ast.aux.Field;
import project.parser.ast.aux.Record;
import project.parser.ast.types.RecordType;
import project.parser.ast.types.Type;
import project.parser.ast.values.RecordValue;

import java.util.HashMap;
import java.util.List;

public class Fields extends AuxExpList<Field> implements Exp {
	public Fields(List<Field> list) {
		super(list);
	}

	public Field get(Ident id) {
		for (Field field : this)
			if (field.getIdent() == id)
				return field;
		return null;
	}

	@Override
	public Type typecheck(StaticEnv senv) {
		HashMap<Ident,Type> typesMap = new HashMap<>();
		for (Field field : list)
			typesMap.put(field.getIdent(), field.typecheck(senv));
		return new RecordType(typesMap);
	}

	@Override
	public Value evaluate(DynamicEnv denv) {
		HashMap<Ident,Value> valuesMap = new HashMap<>();
		for (Field field : list)
			valuesMap.put(field.getIdent(), field.evaluate(denv));
		return new RecordValue(new Record(valuesMap));
	}

	@Override
	public String toString() {
		String superStr = super.toString();
		return "{" + superStr + "}";
	}
}
